import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, DatePicker, message } from 'antd';
import React, { useCallback, useRef, useState, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import moment from 'moment';
import { irregularluggagesummaryTable, downloadluggagesummaryExcel } from '../service';
import styles from './index.less'
import AuthComponent from '@/components/Authorized/AuthComponent';

const Totalcompensation = (props) => {

  const actionRef = useRef();
  const ref = useRef();

  // 是否为第一次加载
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  // 存储搜索条件
  const [searchParams, handleSearchParams] = useState()
  // 表格是否有数据
  const [exportFlag, handleExportFlag] = useState(false)

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {
    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (event.target.querySelector('span').innerText === '重 置') {
      ref.current.setFieldsValue({
        startDate: moment().subtract(1, 'days'),
        endDate: moment()
      })
    }
    handleSearchParams(params)
    return params
  }, []);

  //导出方法
  const handleExport = () => {
    if (!exportFlag) {
      message.warning('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = downloadluggagesummaryExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '异常行李补偿合计表' + time + '.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  const columns = [
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 100,
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      dataIndex: 'startDate',
      order: 7,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '航班结束日期',
      dataIndex: 'endDate',
      order: 6,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '箱包补偿',
      dataIndex: 'baggageCompensateCount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '破损补偿',
      dataIndex: 'damageCompensateCount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '少收补偿',
      dataIndex: 'lessCompensateCount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '内件缺失补偿',
      dataIndex: 'missCompensateCount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '合计补偿',
      dataIndex: 'totalCount',
      width: 100,
      hideInSearch: true
    }
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.totalcompensation}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>补偿合计表</span>
          </div>
        }
        options={{ density: false, fullScreen: true, reload: false, setting: true }}
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          span: 6
        }}
        toolBarRender={() => [
          <AuthComponent authCode="banksearchSystem.totalcompensation.export">
            <Button icon="download" type="primary" onClick={() => handleExport()} size="small">
              导出
            </Button>
          </AuthComponent>
        ]}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          if (!params['startDate'] && !params['endState'] && firstLoadDate) {
            setFirstLoadDate(false)
            params['startDate'] = moment().subtract(1, 'days').format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment().subtract(1, 'days'),
              endDate: moment()
            })
          }
          return irregularluggagesummaryTable(params);
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 800, y: 180 }}
      />
    </>
  );
};

export default Form.create()(Totalcompensation);
